import 'dart:isolate';

///isolate 通信 - 阻塞式 BIO
void main() async {
  print("main begin");

  ReceivePort receivePort = ReceivePort();

  Isolate.spawn(newThread, receivePort.sendPort);

  //await监听会有重复问题，请注意，一个await只能监听一个fd资源
  // SendPort childSendPort = await receivePort.first;
  // SendPort? childSendPort;
  // bool isInitSendPort = false;

  // await for (var message in receivePort) {
  //   if(message is SendPort){
  //     childSendPort = message;
  //   }else{
  //     print("listen方式-主线程接收到消息：$message");
  //     childSendPort?.send("主线程发送给子线程的消息");
  //   }
  //
  // }

  SendPort childSendPort = await receivePort.first;
  var msg = await sendToReceive(childSendPort, "你好");
  print("msg:$msg");

  print("main end");
}

///参数的定义可以随意，参数中接收的SendPort是需要通信的发送端口
///@sendPort
void newThread(SendPort sendPort) async {
  ReceivePort receivePort = ReceivePort();

  //通过传递过来的sendPort给主线程回消息
  print("发送当前isolate端口");
  sendPort.send(receivePort.sendPort);
  //循环当前线程的接收
  await for (var message in receivePort) {
    print("await方式-子线程接收到消息：$message[0]");
    SendPort sendPort = message[1];
    sendPort.send("我是子线程...");
  }
}

Future sendToReceive(SendPort port, msg) {
  print("发送消息给新线程：$msg");
  ReceivePort receivePort = ReceivePort();
  port.send([msg, receivePort.sendPort]);
  return receivePort.first;
}
